package com.ljj.examisto.ui.base

import android.app.Dialog
import android.content.Context
import android.content.res.Configuration
import android.util.Log
import com.ljj.examisto.R
import com.ljj.examisto.util.Logger.TAG

open class BaseDialog : Dialog {
    companion object {
        private var lastShowTime = 0L
        private const val OFFSET = 1.1
    }

    constructor(context: Context, themeResId: Int) : super(context, themeResId) {
        // 设置Dialog跟随Activity销毁
        if (context is android.app.Activity) {
            setOwnerActivity(context)
        }
    }

    override fun show() {
        // 检查所依附的Activity状态
        ownerActivity?.let { activity ->
            if (activity.isFinishing || activity.isDestroyed) {
                return
            }
            try {
                val config = activity.resources.configuration
                if (config.orientation == Configuration.ORIENTATION_UNDEFINED) {
                    return
                }
            } catch (e: Exception) {
                Log.e(TAG, "获取configuration时发生错误: ${e.message}")
                return
            }
        }
        val currentTime = System.currentTimeMillis()
        val threshold = (context.resources.getInteger(R.integer.animation_duration) * 2) * OFFSET
        // 时间间隔防抖动
        if (currentTime - lastShowTime > threshold) {
            try {
                lastShowTime = currentTime
                super.show()
            } catch (e: Exception) {
                Log.e(TAG, "show时发生错误: ${e.message}")
            }
        }
    }
}